package com.kk.app.render;

import android.os.SystemClock;
import android.util.Log;

/**
 * Counter class used to calculate and log the current FPS of frame production.
 */
public class FpsCounter {
    //TODO: Hook this up to SystTrace?
    private static final String TAG = "FpsCounter";
    private int mFrameCount = 0;
    private long mLastTime = 0;
    private long mLastPrintTime = 0;
    private double mLastFps = 0;
    private final String mStreamType;
    private static final long NANO_PER_SECOND = 1000000000; //ns

    public FpsCounter(String streamType) {
        mStreamType = streamType;
    }

    public synchronized void countFrame() {
        mFrameCount++;
        long nextTime = SystemClock.elapsedRealtimeNanos();
        if (mLastTime == 0) {
            mLastTime = nextTime;
        }
        if (nextTime > mLastTime + NANO_PER_SECOND) {
            long elapsed = nextTime - mLastTime;
            mLastFps = mFrameCount * (NANO_PER_SECOND / (double) elapsed);
            mFrameCount = 0;
            mLastTime = nextTime;
        }
    }

    public synchronized double checkFps() {
        return mLastFps;
    }

    public synchronized void staggeredLog() {
        if (mLastTime > mLastPrintTime + 5 * NANO_PER_SECOND) {
            mLastPrintTime = mLastTime;
            Log.d(TAG, "FPS for " + mStreamType + " stream: " + mLastFps );
        }
    }

    public synchronized void countAndLog() {
        countFrame();
        staggeredLog();
    }
}